﻿using doubango_rt.BackEnd;
using System;
using System.Threading.Tasks;
using WinRT.SIP.UILogic.Models;

namespace WinRT.SIP.UILogic.Repositories
{
    public class CallRepository : ICallRepository
    {
        private readonly IDoubangoServer _server = null;

        private ContactInfo _currentContact = null;
        private bool _isIncoming = false;

        public CallRepository(IDoubangoServer server)
        {
            _server = server;
        }

        public void SetCallListener(ICallListener pListener)
        {
            _server.Instance.SipService.SetCallListener(pListener);
        }

        public bool IsIncoming
        {
            get { return _isIncoming; }
        }

        public void SetCurrentCallee(string phoneNumber, bool isIncoming)
        {
            _currentContact = null;

            //TODO: Do a phone number lookup to obtain the contact information.
            if (_currentContact == null)
            {
                _currentContact = new ContactInfo { PhoneNumber = phoneNumber  };
                _isIncoming = isIncoming;
            }
        }

        public string GetCalleeDisplayName()
        {
            if (_currentContact == null)
            {
                return "";
            }
            else
            {
                return _currentContact.DisplayName;
            }
        }

        public async Task MakeCallAsync(string phoneNumber)
        {
            await Task.Run(() =>
            {
                var sipService = _server.Instance.SipService;

                if (sipService != null && sipService.RegistrationState == SipSessionState.Connected)
                {
                    rtSipUri toUri = null;
                    
                    // 3333 - To hear music
                    // 4444 - To test mic
                    // 1233 - To go to voicemail
                    toUri = _server.Instance.rtSipUriNew(string.Format("sip:{0}@sip2sip.info", phoneNumber), "unknown");

                    var call = sipService.MakeCall(toUri, true, null);
                }
            });
        }

        public async Task ReceiveCallAsync()
        {
            //TODO: Receive call from SIP service. Simulate with delay for now.
            await Task.Delay(2000);
        }

        public async Task EndCallAsync()
        {
            //TODO: Call Hangup in the SIP service. Simulate with delay for now.
            await Task.Delay(2000);
        }
    }
}
